//
// Created by martin on 1/28/22.
//

#ifndef MYMUDUO_CURRENTTHREAD_H
#define MYMUDUO_CURRENTTHREAD_H

#include "muduo/base/Types.h"

namespace muduo
{
namespace CurrentThread
{
// thread local
extern __thread int t_cachedTid;
extern __thread char t_tidString[32];
extern __thread int t_tidStringLength;
extern __thread const char* t_threadName;
void cacheTid();

// for compiler optimization
// for gcc/g++
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)

inline int tid()
{
//    if (unlikely(t_cachedTid)) // not 0
    if (__builtin_expect(t_cachedTid == 0, 0))
    {
        cacheTid();
    }
    return t_cachedTid;
}

// for logging
inline const char* tidString()
{
    return t_tidString;
}
inline int tidStringLength()
{
    return t_tidStringLength;
}

inline const char* name()
{
    return t_threadName;
}

bool isMainThread();

void sleepUsec(int64_t usec); // for testing

string stackTrace(bool demangle);

} // namespace CurrentThread
} // namespace muduo

#endif //MYMUDUO_CURRENTTHREAD_H
